﻿using System.Collections.Generic;
using System.Configuration;

namespace Risesun.Extend
{
    public static class ConfigHelper
    {
        private static readonly Dictionary<string, Configuration> Cached = new Dictionary<string, Configuration>();

        public static Configuration Load(string file, ConfigurationUserLevel level = ConfigurationUserLevel.None)
        {
            if (Cached.ContainsKey(file))
            {
                return Cached[file];
            }

            var fileMap = new ExeConfigurationFileMap
            {
                ExeConfigFilename = file
            };

            Configuration configuration = ConfigurationManager.OpenMappedExeConfiguration(fileMap, level);
            
            Cached[file] = configuration;
            
            return configuration;
        }

        public static T Section<T>(this string file, string name) where T : class
        {
            var config = Load(file);
            var section = config.GetSection(name) as T;
            return section;
        }
    }
}